import { localRead } from './util'
import axios, { AxiosRequestConfig } from 'axios'
import router from '../router'
import { Message } from 'view-design'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASEURL
  // baseURL: '/bigdata'
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (router.currentRoute.path === '/login') {
      return config
    }
    if (sessionStorage.getItem("vue_admin_template_token") === null){
      (Message as any)['error']({
        background: true,
        content: '请重新登陆'
      })
      router.push('/login')
      return config
    }
    const time = JSON.parse(localRead('time') || '0')
    const now = new Date().getTime()
    const del = (now - time) % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    const hours = Math.floor(del / (3600 * 1000))
    config.headers["token"] = sessionStorage.getItem(
      "vue_admin_template_token"
    )
    if (!time || hours > 2) {
      router.push('/login')
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
